package com.rzico.sbl.ui.report_029

import android.widget.ImageView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportOrderDetailBinding
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderLogData
import com.rzico.sbl.other.serviceStep
import com.rzico.sbl.other.showOrderLogDialog
import com.rzico.sbl.ui.report.dispatch.ReportDispatchLookActivity
import com.rzico.sbl.ui.report.driver.DriverStationBarrelActivity
import com.rzico.sbl.ui.report.driver.DriverStationMoneyActivity
import com.rzico.sbl.viewmodel.ReportViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.copyStringToClip
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONArray
import org.json.JSONObject

class XAReportOrderDetailActivity : BaseActivity(R.layout.activity_report_order_detail) {

    private val mBinding by lazy { ActivityReportOrderDetailBinding.bind(getRootView()) }

    private val mLogList = arrayListOf<OrderLogData>()
    private var mEnterpriseId = ""
    private var mOrderSn = ""
    private var mOrderStatus = ""
    private var mShipId = ""
    private var mShippingSn = ""
    private var mReceivePhone = ""
    private var mReceiveAdress = ""

    override fun getViewModel() = get<ReportViewModel>()

    override fun initData() {
        initTitle(
            title = intent.getExtra("title")
                .isEmpty()
                .conditionElseValue(
                    actionTrue = { "订单详情" },
                    actionFalse = { "运单详情" }
                )
        )

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding.detailList.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(getIContext())

            addItemDecoration(
                SpaceTBDecoration(
                    top = 5f,
                    hasHeader = false,
                    hasFooter = false,
                    spaceColor = R.color.white
                )
            )

            mAdapter = SlimAdapter.creator()
                .register<OrderGoods>(R.layout.item_order_detail_list) { jector, bean, _ ->
                    jector.apply {
                        text(R.id.item_order_name, bean.name)
                        text(R.id.item_order_type, "规格: ${bean.spec.orEmpty()}")
                        text(R.id.item_order_price, "单价: ${bean.price.formatDecimal()}元")
                        text(R.id.item_order_num, "x${bean.quantity}")

                        with<ImageView>(R.id.item_order_img) {
                            it.loadImage(bean.thumbnail)
                        }
                    }
                }
                .attachTo(this)
        }
    }

    override fun initListener() {
        mBinding.apply {
            detailLogLl.oneClick {
                mLogList.notEmpty {
                    showOrderLogDialog(this)
                }
            }

            detailMoneyLl.oneClick {
                mEnterpriseId.notEmpty {
                    startActivityEx<DriverStationMoneyActivity>(
                        "mode" to "hide",
                        "shopId" to this
                    )
                }
            }

            detailBarrelLl.oneClick {
                mEnterpriseId.notEmpty {
                    startActivityEx<DriverStationBarrelActivity>(
                        "mode" to "hide",
                        "shopId" to this
                    )
                }
            }

            detailCall.oneClick {
                mReceivePhone.notEmpty {
                    showBottomPhoneDialog(this)
                }
            }

            detailAdress.longClick {
                mReceiveAdress.notEmpty {
                    copyStringToClip(this)
                    showToast("地址复制成功！")
                }
            }

            detailAdressCopy.oneClick {
                mReceiveAdress.notEmpty {
                    copyStringToClip(this)
                    showToast("地址复制成功！")
                }
            }

            detailDispatch.oneClick {
                if (mShipId.isNotEmpty()
                    && mShippingSn.isNotEmpty()
                ) {
                    startActivityEx<ReportDispatchLookActivity>(
                        "shipId" to mShipId,
                        "orderSn" to mOrderSn,
                        "shippingSn" to mShippingSn
                    )
                }
            }

            detailNum.longClick {
                mOrderSn.notEmpty {
                    copyStringToClip(this)
                    showToast("订单编号复制成功！")
                }
            }

            detailNumCopy.oneClick {
                mOrderSn.notEmpty {
                    copyStringToClip(this)
                    showToast("订单编号复制成功！")
                }
            }

            detailBtn1.oneClick {
                mOrderSn.notEmpty {
                    showHintDialog(
                        title = "确认订单",
                        hint = "确定要审核订单吗？",
                        onSure = {
                            getViewModel()
                                .confirmOrder(this)
                                .bindLifeCycle(getLifecycleOwner())
                                .subscribeBySuccess(
                                    event = getViewModel(),
                                    onSuccess = {
                                        showToast("订单确认成功！")

                                        // 报货订单刷新
                                        LiveEventBus
                                            .get("orderModify")
                                            .post("confirm")

                                        finishView()
                                    }
                                )
                        }
                    )
                }
            }
        }
    }

    /**
     * 订单详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderDetail(intent.getExtra("orderSn"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mEnterpriseId = obj.optNotNull("enterpriseId")
                    mOrderSn = obj.optNotNull("sn")
                    mOrderStatus = obj.optNotNull("status")
                    mShipId = obj.optNotNull("shippingId")
                    mShippingSn = obj.optNotNull("shippingSn")

                    mBinding.apply {
                        detailBottom.isVisible = (
                                intent.getExtra("mode") == "confirm"
                                        && mOrderStatus in "unpaid")

                        detailTotal.text = obj.optNotNull("quantity")
                        detailAmount.text = obj.optNotNull("price").formatDecimal()

                        // 商品小计
                        obj.optNotNull("memo").apply {
                            val items = split("|")
                            detailHint.text = items[0].replace(";", ";\n")
                            if (items.size > 1) {
                                detailMai.text =
                                    items[1].notEmpty { detailMaiLl.visible() }
                            }
                        }
                        // 代金券(一)
                        obj.optNotNull("couponDiscount")
                            .also {
                                if (it.intValue != 0) {
                                    detailCoupon1Ll.visible()
                                    detailCoupon1.text =
                                        "–${(it.intValue * 0.3).formatDecimal()}元 ($it * 0.3)"
                                }
                            }
                        // 代金券(二)
                        obj.optNotNull("vipDiscount")
                            .also {
                                if (it.intValue != 0) {
                                    detailCoupon2Ll.visible()
                                    detailCoupon2.text =
                                        "–${(it.intValue * 0.3).formatDecimal()}元 ($it * 0.3)"
                                }
                            }
                        // 代金券(三)
                        obj.optNotNull("exchangeDiscount")
                            .also {
                                if (it.intValue != 0) {
                                    detailCoupon3Ll.visible()
                                    detailCoupon3.text =
                                        "–${(it.intValue * 2.0).formatDecimal()}元 ($it * 2.0)"
                                }
                            }
                        // 运费
                        obj.optNotNull("freight")
                            .also {
                                if (it.doubleValue > 0) {
                                    detailFeeLl.visible()
                                    detailFee.text = "+${it.formatDecimal()} 元"
                                }
                            }
                        // 订单合计
                        detailPrice.text = "${obj.optNotNull("amountPayable").formatDecimal()} 元"
                        // 重量合计
                        detailWeight.text = "${obj.optNotNull("weight")} kg"

                        /*---------------------- 客户信息 ----------------------*/
                        val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                        mReceivePhone = objReceive.optNotNull("phone")
                        mReceiveAdress = objReceive.optNotNull("address")
                        // 姓名
                        detailName.text = objReceive.optNotNull("consignee")
                        // 电话
                        detailPhone.text = mReceivePhone
                        // 收货地址
                        detailAdress.text = mReceiveAdress
                        // 买家欠款
                        detailMoney.text =
                            obj.optNotNull("arrears")
                                .also {
                                    detailMoneyLl.visible()
                                }.formatDecimal()
                        // 买家欠桶
                        detailBarrel.text =
                            obj.optNotEmpty("borrow", "0")
                                .also {
                                    detailBarrelLl.visible()
                                }

                        /*---------------------- 订单信息 ----------------------*/
                        // 订单状态
                        detailStatus.text = obj.optNotNull("statusDescr")
                        // 订单编号
                        detailNum.text = mOrderSn
                        // 支付方式
                        detailPay.text =
                            obj.optNotNull("paymentMethod")
                                .notEmpty { detailPayLl.visible() }
                        // 销售站点
                        detailShou.text =
                            obj.optNotNull("sellerName")
                                .notEmpty { detailShouLl.visible() }
                        // 下单时间
                        detailCreate.text =
                            obj.optNotNull("createDate")
                                .getTimeString()
                        // 预约时间
                        detailYue.text =
                            obj.optNotNull("hopeDate")
                                .notEmpty { detailYueLl.visible() }
                                .getTimeString()
                        // 发货时间
                        detailFa.text =
                            obj.optNotNull("shippingDate")
                                .notEmpty { detailFaLl.visible() }
                                .getTimeString()
                        // 送达时间
                        detailDa.text =
                            obj.optNotNull("deliveryDate")
                                .notEmpty { detailDaLl.visible() }
                                .getTimeString()
                        // 交易完成
                        detailWan.text =
                            obj.optNotNull("completeDate")
                                .notEmpty { detailWanLl.visible() }
                                .getTimeString()
                        // 送达明细
                        when (serviceStep) {
                            "2", "3" ->
                                if (mOrderStatus == "completed")
                                    detailDispatch.visible()
                        }
                        // 派单留言
                        detailPai.text =
                            obj.optNotNull("shippingMemo")
                                .trimEnd('\n')
                                .notEmpty { detailPaiLl.visible() }
                        // 配送方式
                        detailDeliver.text =
                            obj.optNotNull("shippingMethod")
                                .notEmpty { detailDeliverLl.visible() }
                        // 配送站点
                        detailZhan.text =
                            obj.optNotNull("shopName")
                                .notEmpty { detailZhanLl.visible() }
                        // 配送人员
                        detailRen.text =
                            obj.optNotNull("adminName")
                                .notEmpty { detailRenLl.visible() }

                        /*---------------------- 订单状态 ----------------------*/
                        val objLog = obj.optJSONArray("orderLogs") ?: JSONArray()
                        mLogList.apply {
                            clear()
                            addItems(
                                JsonUtil.toList<OrderLogData>(
                                    objLog.toString(),
                                    OrderLogData::class.java
                                ).reversed()
                            )
                        }
                        detailLog1.text = mLogList[0].createDate.getTimeString()
                        detailLog2.text = mLogList[0].content
                    }

                    /*---------------------- 商品信息 ----------------------*/
                    val objOrder = obj.optJSONArray("orderItems") ?: JSONArray()
                    mList.clear()
                    mList.addItems(
                        JsonUtil.toList(
                            objOrder.toString(),
                            OrderGoods::class.java
                        )
                    )
                    mAdapter.setDataList(mList)
                }
            )
    }

}